<?php

namespace app\api2\controller;

use think\Controller;
use think\Request;
use app\common\controller\UtilController;
use app\common\model\Member;
use think\Cache;

class LoginController extends Controller
{
	public $Success = true;
	public $Msg = "";
	public $Data = "";
    //登录验证
    public function index()
    {
    	//关注和没关注 都可以获取code
		$code = Request::instance()->get('code');
		//通过code获取openid
		$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx9f07a1d30dfc65cc&secret=e9b5bbc1ae2f3ab7f61a1243ddf86da2&code='.$code.'&grant_type=authorization_code ';
		$util = new UtilController();
		$content = $util->GetUrl($url);
		$content = json_decode($content); 
		if(!property_exists($content,'errmsg'))
		{
			$result = Member::where(['openid'=>$content->openid])->find();
		}
		if(!empty($result))
		{
			//该用户已经绑定微信公众号了  直接跳转个人信息中心   传值给前端access_token
			$token = uniqid();
			Cache::set($token, $result->id,3600);
			$data['access_token'] = $token;
			return UtilController::jsonResponse(['Success'=>$this->Success,'Msg'=>$this->Msg,'Data'=>$data]);
		}
    	$name = Request::instance()->get('name');
    	$passwd = Request::instance()->get('passwd');
    	if(empty($name))
    	{
    		$this->Success = false;
    		$this->Msg = "填写用户名!";
    		return UtilController::jsonResponse(['Success'=>$this->Success,'Msg'=>$this->Msg]);
    	}
    	if(empty($passwd))
    	{
    		$this->Success = false;
    		$this->Msg = "密码不能为空!";
    		return UtilController::jsonResponse(['Success'=>$this->Success,'Msg'=>$this->Msg]);
    	}
    	if(UtilController::isMobile($name))
    	{
    		$result = Member::where(['mobile'=>$name,'passwd'=>md5($passwd)])->find();
    		if(!empty($result))
    		{
    			$this->Msg = "用户登录成功!";
				$token = uniqid();
				Cache::set($token, $result['id'],3600);
				$data['access_token'] = $token;
				return UtilController::jsonResponse(['Success'=>$this->Success,'Msg'=>$this->Msg,'Data'=>$data]);
    		}
    	}
    	//公爵号登录
    	$result = Member::where(['duke'=>$name,'passwd'=>md5($passwd)])->find();
    	if(!empty($result))
    	{
    		$this->Msg = "用户登录成功!";
    		$token = uniqid();
    		Cache::set($token, $result['id'],3600);
    		$data['access_token'] = $token;
    		return UtilController::jsonResponse(['Success'=>$this->Success,'Msg'=>$this->Msg,'Data'=>$data]);
    	}else{
    		$this->Success = false;
    		$this->Msg = "用户名或者密码错误!";
    		return UtilController::jsonResponse(['Success'=>$this->Success,'Msg'=>$this->Msg]);
    	}
    	
    }
    
  
}
